import store from "../store";

Date.prototype.Format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
let getAnimation = function() {
    let lastTime = 0;
    let vendors = ['webkit', 'moz'];
    for(let x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
        window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
        window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] ||    // Webkit中此取消方法的名字变了
            window[vendors[x] + 'CancelRequestAnimationFrame'];
    }

    if (!window.requestAnimationFrame) {
        window.requestAnimationFrame = function(callback) {
            let currTime = new Date().getTime();
            let timeToCall = Math.max(0, 16.7 - (currTime - lastTime));
            let id = window.setTimeout(function() {
                callback(currTime + timeToCall);
            }, timeToCall);
            lastTime = currTime + timeToCall;
            return id;
        };
    }
    if (!window.cancelAnimationFrame) {
        window.cancelAnimationFrame = function(id) {
            clearTimeout(id);
        };
    }
};
getAnimation();
/* istanbul ignore next */
const trim = function(string) {
    return (string || '').replace(/^[\s\uFEFF]+|[\s\uFEFF]+$/g, '');
};
export const on = (function() {
    if (document.addEventListener) {
        return function(element, event, handler) {
            if (element && event && handler) {
                element.addEventListener(event, handler, false);
            }
        };
    } else {
        return function(element, event, handler) {
            if (element && event && handler) {
                element.attachEvent('on' + event, handler);
            }
        };
    }
})();
//为节点添加监听事件

export const off = (function() {
    if (document.removeEventListener) {
        return function(element, event, handler) {
            if (element && event) {
                element.removeEventListener(event, handler, false);
            }
        };
    } else {
        return function(element, event, handler) {
            if (element && event) {
                element.detachEvent('on' + event, handler);
            }
        };
    }
})();
//删除节点的监听事件

/* istanbul ignore next */
export function hasClass(el, cls) {
    if (!el || !cls) return false;
    if (cls.indexOf(' ') !== -1) throw new Error('className should not contain space.');
    if (el.classList) {
        return el.classList.contains(cls);
    } else {
        return (' ' + el.className + ' ').indexOf(' ' + cls + ' ') > -1;
    }
}
/* istanbul ignore next */
export function addClass(el, cls) {
    if (!el) return;
    let curClass = el.className;
    let classes = (cls || '').split(' ');

    for (let i = 0, j = classes.length; i < j; i++) {
        let clsName = classes[i];
        if (!clsName) continue;

        if (el.classList) {
            el.classList.add(clsName);
        } else if (!hasClass(el, clsName)) {
            curClass += ' ' + clsName;
        }
    }
    if (!el.classList) {
        el.className = curClass;
    }
}

/* istanbul ignore next */
export function removeClass(el, cls) {
    if (!el || !cls) return;
    let classes = cls.split(' ');
    let curClass = ' ' + el.className + ' ';

    for (let i = 0, j = classes.length; i < j; i++) {
        let clsName = classes[i];
        if (!clsName) continue;

        if (el.classList) {
            el.classList.remove(clsName);
        } else if (hasClass(el, clsName)) {
            curClass = curClass.replace(' ' + clsName + ' ', ' ');
        }
    }
    if (!el.classList) {
        el.className = trim(curClass);
    }
}
/*处理图片数据*/
export function HandledPhoto (data, h, w) {
    if(!data) return '';
    let arr = JSON.parse(data);
    if(arr.length === 0) return '';
    return `${arr[0].URL}?x-oss-process=image/resize,m_pad,h_${h},w_${w}`;
}
/*处理颜色尺寸的数据*/
function disposeData (data, cb, sortCb) {
    let detail = {};
    data.map(obj => {
        cb(detail, obj)
    })
    let arr = Object.keys(detail).map(obj => detail[obj])
    if(sortCb) return arr.sort(sortCb);
    return arr;
}

/*返回处理完成的颜色尺寸集合*/
export function dealColorSize (imgList, skuList) {
    //筛选出所有颜色
    let colors = disposeData(skuList, (detail, obj) => {
        detail[obj.clrCode] = {
            id: obj.clrCode,
            label: obj.clrName
        }
    }, (a, b) => a.id - b.id);
    let detail = {};
    //筛选出所有尺寸
    detail.size = disposeData(skuList, (detail, obj) => {
        detail[obj.sizeCode] = {
            id: obj.sizeCode,
            label: obj.sizeName
        }
    }, (a, b) => a.id - b.id);
    //一一对应
    detail.data = colors.map(obj => {
        let arr = [];
        let img = imgList.find(n => n.ECODE === obj.id);
        detail.size.map(size => {
            let count = skuList.find(n => n.sizeCode === size.id && obj.id === n.clrCode);
            arr.push({
                skuCode: count? count.skuCode : 0,
                skuId: count? count.skuId : 0,
                stdSkuId: count? count.stdSkuId : 0,
                new: count? count.qtyDisplay : 0,
                old: count? count.qtyDisplay : 0
            })
        })
        return {
            label: obj.label,
            img: img && img.URL? `${img.URL}?x-oss-process=image/resize,m_pad,h_30,w_30` : '',
            count: arr
        }
    })
    return detail;
}
/*动态获取门店id*/
export function getUserId() {
    let data = {};
    let search = window.location.search && window.location.search.split('?');
    if(search) {
        search[1].split('&').map(obj => {
            data[obj.split('=')[0]] = obj.split('=')[1];
        })
    }
    if(data.str_id) {
        localStorage.setItem('str_id', data.str_id);
    }else {
        data.str_id = localStorage.getItem('str_id');
    }
    data.str_id? store.commit('dynamicSetUerId', data.str_id) : '';
}

/* 是否为无效值 */
export function isInvalid(val) {
    return val === '' || val === null || val === undefined;
}

export function debounce(delay, fn) {
    let timerId = null;
    function warp(...args) {
        try {
            let context = this;
            if(timerId) clearTimeout(timerId);
            let func = function () {
                fn && fn.call(context, ...args);
            }
            timerId = setTimeout(func, delay);
        }catch (e) {

        }
    }
    return warp
}
